import { createRouter, createWebHistory } from 'vue-router'

import Login from '@/views/Login/index.vue'

import Loading from '@/components/Loading.vue'
import Empty from '@/components/Empty.vue'
import Home from '@/views/Home/index.vue'

import Register from '@/views/Register/Register.vue'

import UserCenter from '@/views/User/UserCenter.vue'
import EditUserInfo from '@/views/User/EditUserInfo.vue'
import UserFollowList from '@/views/User/UserFollowList.vue'
import AdminIndex from '@/views/Admin/index.vue' // 管理员主页面
import AdminMain from '@/views/Admin/AdminMain.vue' // 管理员主面板
import AdminProfile from '@/views/Admin/AdminProfile.vue' // 管理员资料
import Check from '@/views/Admin/check/Check.vue' // 审核文章
import Report from '@/views/Admin/report/Report.vue'
import Fav from '@/views/User/FavContent.vue'
import History from '@/views/User/HistoryContent.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
    },
    {
      path: '/home',
      component: Home,
      children: [
        { path: '', redirect: 'dynamic' },
        {
          path: 'dynamic',
          component: () => import('@/views/Dynamic/index.vue'),
        },
        {
          path: 'article',
          component: () => import('@/views/Article/index.vue'),
        },
        {
          path: 'article/:articleId', // 动态参数
          component: () => import('@/views/Article/detail.vue'),
        },
        {
          path: 'reading',
          component: () => import('@/views/Reading/ReadingLayout.vue'),
          children: [
            {
              path: '',
              redirect: '/home/reading/bookshelf', // ✅ 显式写全路径
            },
            {
              path: 'library',
              component: () => import('@/views/Reading/LibraryView.vue'),
            },
            {
              path: 'bookshelf',
              component: () => import('@/views/Reading/BookshelfView.vue'),
            },
            {
              path: 'book/:bookId',
              component: () => import('@/views/Reading/BookDetail.vue'),
            },
            {
              path: 'book/:bookId/characters',
              name: 'bookCharacters',
              component: () => import('@/views/Reading/BookCharacters.vue'),
            },
            {
              path: 'book/:bookId/chapters',
              name: 'bookChapters',
              component: () => import('@/views/Reading/ChapterList.vue'),
            },
          ],
        },
        {
          path: '/home/topic/:id',
          name: 'TopicDetail',
          component: () => import('@/views/Topic/TopicDetail.vue'),
          props: true,
        },

        {
          path: 'dynamic/:id',
          component: () => import('@/views/Dynamic/Detail.vue'), // ✅ 详情页也放进来
        },
        {
          path: 'message',
          component: () => import('@/views/message/index.vue'),
          meta: { requiresAuth: true },
        },

        {
          path: 'user/:userId',
          component: UserCenter,
          children: [
            {
              path: 'edit',
              component: EditUserInfo, // 编辑资料组件
            },
            {
              path: 'follow', // 👈 这里就是新增的关注/粉丝页面
              component: UserFollowList,
            },
            {
              path: 'fav',
              component: Fav,
            },
            {
              path: 'history',
              component: History,
            },
          ],
        },
      ],
    },
    {
      path: '/admin',
      component: AdminIndex, // 新增的管理员面板
      meta: { requiresAuth: true, role: '2' }, // 需要判断是否为管理员
      children: [
        {
          path: '',
          component: AdminMain, // 管理员主页
          name: 'AdminMain',
        },
        {
          path: 'profile',
          component: AdminProfile, // 管理员资料
          name: 'AdminProfile',
        },
        {
          path: 'check',
          component: Check, // 审核文章页面
          name: 'Check',
        },
        {
          path: 'report',
          component: Report, // 审核评论页面
          name: 'Report',
        },
      ],
    },
    {
      path: '/creator',
      component: () => import('@/views/Editor/CreatorLayout.vue'), // 创建一个新的布局组件
      children: [
        {
          path: 'image-text-editor/:id?', // 图文发布编辑页面
          component: () => import('@/views/Editor/DynamicEditor.vue'), // 图文编辑页面
          meta: { requiresAuth: true },
        },
        {
          path: 'article-editor/:id?', // 文章发布编辑页面
          component: () => import('@/views/Editor/ArticleEditor.vue'), // 文章编辑页面
          meta: { requiresAuth: true },
        },
        {
          path: 'content-management',
          component: () => import('@/views/Editor/ContentManagement.vue'), // 内容管理页面
        },
      ],
    },
    {
      path: '/book/:bookId/chapter/:chapterId',
      name: 'bookChapter',
      component: () => import('@/views/Reading/ChapterDetail.vue'),
    },

    {
      path: '/empty',
      component: Empty,
    },
    {
      path: '/register',
      component: Register,
    },

    {
      name: 'login',
      path: '/login',
      component: Login,
    },
    {
      path: '/loading',
      component: Loading,
    },
  ],
})

// 路由守卫
const whitePathList = ['/login', '/register'] // ✅ 用 path 来判断更稳定

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userType = localStorage.getItem('type') // 1 表示普通用户，2 表示管理员
  const isWhite = whitePathList.some((path) => to.path.startsWith(path))

  // 未登录用户，且访问非白名单路径
  if (!isWhite && !token) {
    return next({ path: '/login' })
  }

  // 如果访问根路径，根据用户类型动态跳转
  if (to.path === '/') {
    if (userType === '2') {
      return next('/admin')
    } else {
      return next('/home/dynamic')
    }
  }

  // 如果访问需要特定角色的页面，但用户角色不匹配，重定向首页
  if (to.meta.role && to.meta.role !== userType) {
    return next('/')
  }

  next()
})

export default router
